<template>
  <div>
    <table-search
      ref="tableSearch"
      title="报备记录"
      selection
      :columns="columns"
      :api="getList"
      :tabs-options="tabsOptions"
      @selection-change="onSelectionChange"
    >

      <div slot="table-title" style="text-align: right; flex: 1">
        <el-button
          type="primary"
          size="mini"
          @click="onExport"
          :disabled="!selection.length"
        >导出选中记录</el-button>
      </div>

      <template #createTime="{ row }">
        {{row.createTime | dateFilterToDay2}}
      </template>

      <template #filingState="{ row }">
        <div class="hasEdit" v-if="row.modifyStatus">
          <span class="text">改</span>
        </div>
        <p :class="{'red': row.filingState < 4,'grey': row.filingState > 4 }">{{ code2name(row.filingState, goodsStatusList)}}</p>
        <el-button @click="showAuditRecord(row.reportGoodId)" type="text" size="small" style="margin-left: 1.5em">
          审核记录
          <i class="el-icon-arrow-right"></i>
        </el-button>
      </template>

      <template #operate="{ row }">
        <div>
          <router-link :to="`/customer/goods/detail?id=${row.reportGoodId}`" target="_blank">
            <el-button type="text" size="small">查看详情</el-button>
          </router-link>

          <el-button
            style="margin-left: 10px;"
            type="text"
            size="small"
            @click="onEditGoods(row)"
          >修改信息</el-button>

        </div>
        <div>
          <el-popconfirm v-if="row.filingState == 2" title="确认要申请下架此商品吗？" @onConfirm="onUpdateState(row, 3)">
            <el-button slot="reference" type="text" size="small" >申请下架</el-button>
          </el-popconfirm>
          <el-popconfirm v-else title="确认要申请上架此商品吗？" @onConfirm="onUpdateState(row, 1)">
            <el-button slot="reference" type="text" size="small" :disabled="row.filingState != 4" >申请上架</el-button>
          </el-popconfirm>

          <el-popconfirm title="确认要取消此商品报备吗？" @onConfirm="onCancel(row)">
            <el-button style="margin-left: 10px;" slot="reference" :disabled="!(row.filingState == 1 || row.filingState == 4 || row.filingState == 5)" type="text" size="small">取消报备</el-button>
          </el-popconfirm>
        </div>
      </template>
    </table-search>
    <el-dialog title="审核记录" :visible.sync="auditRecordState.show" width="60%">
      <el-table
        v-loading="auditRecordState.loading"
        :data="auditRecordState.data"
        border
        :header-cell-style="{ backgroundColor: '#f5f5f5', color: '#333', fontWeight: 'bold', textAlign:'center' }"
        max-height="500"
      >
        <el-table-column align="center" label="时间" width="200">
          <template slot-scope="scope">{{scope.row.operatorTime | dateFilter}}</template>
        </el-table-column>
        <el-table-column property="operator" label="操作人" width="150" align="center"></el-table-column>
        <el-table-column label="审核状态" width="100" align="center">
          <template slot-scope="scope">{{code2name(scope.row.auditStatus, goodsAuditStatusList)}}</template>
        </el-table-column>
        <el-table-column label="详情">
          <template slot-scope="scope">
            <!-- <el-row v-for="(item,index) in scope.row.auditDetail" :key="index"> -->
            <div class="audit-detail" v-html="scope.row.auditDetail"></div>
            <!-- </el-row> -->
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <GoodsForm
      v-if="editGoods.isEditNum"
      isTitle
      :isEditWindow="editGoods"
      @closedWindow="onEditGoodsClose"
      @editData="onEditGoodsSave"
    ></GoodsForm>

  </div>
</template>

<script>
import { defineComponent, computed, reactive, getCurrentInstance, ref } from '@vue/composition-api'
import GoodsForm from '@/components/goods/form'
import TableSearch from '@/components/TableSearch/TableSearch'
import { createTableColumns } from '@/components/TableSearch/utils'
import dict from '@/lib/dict'
import { useProjectSelectOption } from '@/hooks/project'

import { page, recordList, updateState, update } from '@/api/goodsReport'

import { downLoadFile } from '@/lib/utils'
import Http from '@/lib/http'

const { goodsStatusList, goodsAuditStatusList } = dict

export default defineComponent({
  components: {
    TableSearch,
    GoodsForm,
  },
  setup () {
    const instance = getCurrentInstance()

    const projectSelectOption = useProjectSelectOption()

    const columns = computed(() => {
      return createTableColumns([
        ['商品报备编号', 'reportGoodId', { search: true }],
        ['创建时间', 'createTime', { search: { key: ['createTimeStart', 'createTimeEnd'] }, width: 160 }],
        ['项目名称', 'purchasePlatformName', { search: { key: 'purchasePlatformId', type: 'select', options: projectSelectOption.value } }],
        ['商品名称', 'goodsName', { search: true }],
        ['类目', 'categoryName', { search: true }],
        ['品牌', 'brandName', { sort: 8, search: true }],
        ['数量', 'num'],
        ['备注', 'remark'],
        ['报备状态', 'filingState'],
        ['sku商品编号', 'skuId', { sort: 9, search: true }],
        ['操作', 'operate'],
      ])
    })

    const tabsOptions = reactive({
      list: [{ code: 'all', desc: '全部报备' }, ...goodsStatusList],
      data: {},
      searchKey: 'filingState',
    })

    const code2name = (code, list) => {
      for (const item of list) {
        if (item.code == code) {
          return item.desc
        }
      }
    }

    const getList = async (pageIndex, pageSize, query) => {
      const result = await page({
        pageIndex,
        pageSize,
        ...query,
      })
      getDataCount(result.goodsReportCount)
      return result.pageResult
    }

    const getDataCount = async (result) => {
      // 竞价报备状态(1.申请上架 2.已上架 3.申请下架 4.已下架 5.未通过 6.已取消)
      const dataKeyMap = {
        1: 'applyShelves',
        2: 'onShelves',
        3: 'applyOutShelves',
        4: 'outShelves',
        5: 'notPass',
        6: 'cancel',
        all: 'totalCount',
      }
      const data = {}
      tabsOptions.list.forEach(item => {
        data[item.code] = result[dataKeyMap[item.code]]
      })
      tabsOptions.data = data
    }

    // 审核记录
    const auditRecordState = reactive({
      show: false,
      loading: false,
      id: null,
      data: [],
    })
    const showAuditRecord = async id => {
      auditRecordState.show = true
      // if (id !== auditRecordState.id) {
      auditRecordState.id = id
      auditRecordState.loading = true
      const result = await recordList(id)
      auditRecordState.data = result.map(item => {
        console.log('item.auditDetail', item.auditDetail)
        // item.auditDetail = JSON.parse(item.auditDetail)
        return item
      })
      auditRecordState.loading = false
      // }
    }

    const onCancel = async (item) => {
      const loading = instance.$loading()
      try {
        await updateState(item.reportGoodId, 6)
        instance.$message({
          type: 'success',
          message: '取消报备成功',
        })
        instance.$refs.tableSearch.reload()
      } catch (error) {
        console.error(error)
      }
      loading.close()
    }

    const onUpdateState = async (item, state) => {
      const loading = instance.$loading()
      try {
        await updateState(item.reportGoodId, state)
        instance.$message({
          type: 'success',
          message: '操作成功',
        })
        instance.$refs.tableSearch.reload()
      } catch (error) {
        console.error(error)
      }
      loading.close()
    }

    // 修改信息
    const editGoods = reactive({
      loading: null,
      isEditNum: null, // 要编辑的商品序号
      isEditId: 0, // 要编辑的商品id
      data: null,
    })
    const onEditGoods = (data) => {
      console.log('data', data)
      editGoods.isEditNum = data.reportGoodId
      editGoods.isEditId = data.reportGoodId
      editGoods.data = data
    }

    const onEditGoodsClose = () => {
      if (!editGoods.loading) {
        editGoods.isEditNum = false
      }
    }

    const onEditGoodsSave = async (data) => {
      editGoods.loading = instance.$loading()

      try {
        await update(data)
        instance.$message.success('修改成功')
        editGoods.isEditNum = false
        instance.$refs.tableSearch.reload()
      } catch (error) {

      } finally {
        editGoods.loading.close()
        editGoods.loading = null
      }
    }

    const selection = ref([])
    const onSelectionChange = (val) => {
      selection.value = val
    }

    const onExport = () => {
      downLoadFile(Http.getUrl(`/goods/report/export?ids=${selection.value.map(item => item.id).join(',')}`))
    }

    return {
      columns,
      getList,
      tabsOptions,
      auditRecordState,
      showAuditRecord,
      onCancel,
      onUpdateState,
      goodsStatusList,
      goodsAuditStatusList,
      code2name,
      editGoods,
      onEditGoods,
      onEditGoodsSave,
      onEditGoodsClose,
      onSelectionChange,
      onExport,
      selection,
    }
  },
})
</script>

<style lang="scss" scoped>
.grey {
  color: #bbb;
}
.red {
  color: red;
}
.hasEdit {
  position: absolute;
  top: 0;
  left: 0;
  &::before {
    content: '';
    display: block;
    width: 0;
    height: 0;
    border-top: 30px solid red;
    border-right: 30px solid transparent;
  }
  .text {
    position: absolute;
    top: -3px;
    left: 2px;
    color: #fff;
    font-size: 12px;
  }
}
.audit-detail {
  color: #000;
}
.audit-detail ::v-deep strong {
  color: red;
}
</style>
